package com.quktzhuanka.app.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.github.anzewei.parallaxbacklayout.ParallaxHelper;
import com.google.gson.GsonBuilder;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.quktzhuanka.app.MainActivity;
import com.quktzhuanka.app.R;
import com.quktzhuanka.app.adapter.ShopRecyclerAdapter;
import com.quktzhuanka.app.adapter.TodayHighlightsAdapter;
import com.quktzhuanka.app.base.BaseActivity;
import com.quktzhuanka.app.bean.HaoDanBean;
import com.quktzhuanka.app.bean.TodayHighlightsBean2;
import com.quktzhuanka.app.common.SPUtils;
import com.quktzhuanka.app.config.Constants;
import com.quktzhuanka.app.https.HttpUtils;
import com.quktzhuanka.app.login.WelActivity;
import com.quktzhuanka.app.my.JifenPutForwardActivity;
import com.quktzhuanka.app.my.LingqianPutForwardActivity;
import com.quktzhuanka.app.my.MyShareUrlActivity;
import com.quktzhuanka.app.my.PutForwardActivity;
import com.quktzhuanka.app.utils.AndroidJs;
import com.quktzhuanka.app.utils.JifenUtils;
import com.qq.e.ads.cfg.VideoOption;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.ads.interstitial2.UnifiedInterstitialMediaListener;
import com.qq.e.comm.managers.GDTADManager;
import com.qq.e.comm.util.AdError;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class WebViewActivityz extends BaseActivity {
    @BindView(R.id.bg_head)
    LinearLayout bg_head;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.wv)
    WebView wv;
    private RelativeLayout mFrameLayout;
    private int cid = 0;   // 功能配置id
    int is_video_id = 0;
    boolean is_video_ylh = false;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;


    // 赚咖返回按钮
    Boolean back_flog = false;
    private static final int COMPLETED = 0;
    private static final int COMPLETED1 = 1;
    // 是否是  首页进入
    Boolean main_status = false;


    // 翻倍积分数
    String pointdouble = "";


    private UnifiedInterstitialAD iad;
    private UnifiedInterstitialADListener  unia= new UnifiedInterstitialADListener() {
        @Override
        public void onADReceive() {
            iad.setMediaListener(unim);
            // Toast.makeText(WebViewActivityt.this, "onADReceive", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onVideoCached() {
//            // Toast.makeText(WebViewActivityt.this, "onVideoCached", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onNoAD(AdError adError) {
//            // Toast.makeText(WebViewActivityt.this, "onNoAD", Toast.LENGTH_LONG).show();
            iad = getIAD();
            setVideoOption();
            iad.loadFullScreenAD();

        }

        @Override
        public void onADOpened() {

            iad = getIAD();
            setVideoOption();
            iad.loadFullScreenAD();
            // Toast.makeText(WebViewActivityt.this, "onADOpened", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onADExposure() {
//            // Toast.makeText(WebViewActivityt.this, "onADExposure", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onADClicked() {
//            // Toast.makeText(WebViewActivityt.this, "离开了", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onADLeftApplication() {
//            // Toast.makeText(WebViewActivityt.this, "onADLeftApplication", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onADClosed() {
//            // Toast.makeText(WebViewActivityt.this, "onADClosed", Toast.LENGTH_LONG).show();
            if(is_video_ylh){
                if(cid == 15){  // 翻倍
                    is_video_ylh = false;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        wv.evaluateJavascript("javascript:window.tosingin_double();", null);
                    } else {
                        wv.loadUrl("javascript:window.tosingin_double();");
                    }
                }else{
                    JifenUtils.record_num(WebViewActivityz.this,cid);
                    is_video_ylh = false;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        wv.evaluateJavascript("javascript:window.getData();", null);
                    } else {
                        wv.loadUrl("javascript:window.getData();");
                    }
                }
            }
        }
    };

    private UnifiedInterstitialMediaListener unim = new UnifiedInterstitialMediaListener() {
        @Override
        public void onVideoInit() {

        }

        @Override
        public void onVideoLoading() {

        }

        @Override
        public void onVideoReady(long l) {

        }

        @Override
        public void onVideoStart() {

        }

        @Override
        public void onVideoPause() {

        }

        @Override
        public void onVideoComplete() {
//            // Toast.makeText(WebViewActivityt.this, "结束了 ！ ", Toast.LENGTH_LONG).show();
            is_video_ylh = true;
        }

        @Override
        public void onVideoError(AdError adError) {

        }

        @Override
        public void onVideoPageOpen() {

        }

        @Override
        public void onVideoPageClose() {

        }
    };
    private void setVideoOption() {
        VideoOption.Builder builder = new VideoOption.Builder();
        VideoOption option = builder.setAutoPlayMuted(false).build();
        iad.setVideoOption(option);
//         iad.setVideoPlayPolicy(NativeExpressDemoActivity.getVideoPlayPolicy(option.getAutoPlayPolicy(), this));
    }

    private UnifiedInterstitialAD getIAD() {
        if (this.iad != null) {
            iad.close();
            iad.destroy();
            iad = null;
        }
        iad = new UnifiedInterstitialAD(this, Constants.YLH_ADV, unia);
        return iad;
    }

    private void showFullScreenVideoAD() {
        if (iad != null) {
            iad.showFullScreenAD(this);
        } else {
            // Toast.makeText(this, "请加载广告后再进行展示 ！ ", Toast.LENGTH_LONG).show();
        }
    }
    private BroadcastReceiver lockVideoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            is_video_id = intent.getIntExtra("is_video_id",0);
            wv.post(new Runnable() {
                @Override
                public void run() {
                    if(is_video_id == 10){  // 开始挖
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            wv.evaluateJavascript("javascript:window.setToken_hand_time();", null);
                        } else {
                            wv.loadUrl("javascript:window.setToken_hand_time();");
                        }
                    }else if(is_video_id == 11){  // 收取宝石
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                            wv.evaluateJavascript("javascript:window.getGatherGem();", null);
                        } else {
                            wv.loadUrl("javascript:window.getGatherGem();");
                        }
                    }
                }
            });
        }
    };

    private ShopRecyclerAdapter shopRecyclerAdapter;
//    @BindView(R.id.recyclerView)
//    RecyclerView recyclerView;
//    @BindView(R.id.refresh_layout)
//    SmartRefreshLayout refreshLayout;
    private int page1=1;
    private String min_id = "1";

    private List<TodayHighlightsBean2> todayHighlightsBeans = new ArrayList<>();
    private List<HaoDanBean> todayHighlightsBeans2 = new ArrayList<>();
    private TodayHighlightsAdapter highlightsAdapter;
    List<HaoDanBean> taobaoGuesChildtBeans = new ArrayList<>();

    private boolean isReloadFinshed = false;
    private boolean isreload = true;

    @Override
    protected void initUI() {
        setContentView(R.layout.ac_webviewz);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    protected void initData() {

        SharedPreferences sharedPreferences = getSharedPreferences("JS_CACHE_DATA",MODE_PRIVATE);
        this.isReloadFinshed = sharedPreferences.getBoolean("isReloadFinshed",false);
        isreload = false;


        GDTADManager.getInstance().initWith(this,  Constants.YLH_APPID);

        iad = getIAD();
        setVideoOption();
        iad.loadFullScreenAD();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qwg.VideoComplete");
        this.registerReceiver(this.lockVideoReceiver,intentFilter);

        ParallaxHelper.disableParallaxBack(this);
        mFrameLayout =findViewById(R.id.mFrameLayout);
//        bg_head.setBackground(getResources().getDrawable(R.drawable.bg_user_top));
        tvLeft.setVisibility(View.VISIBLE);
        tvTitle.setText(getIntent().getStringExtra("title"));
        if ("1".equals(getIntent().getStringExtra("status"))){    // 首页进入
            main_status = true;
        }
//        if ("28".equals(getIntent().getStringExtra("cid"))){    // 赚咖联盟
//            tvRight.setVisibility(View.VISIBLE);
//            tvLeft.setTextColor(this.getResources().getColor(R.color.white));
//            tvTitle.setTextColor(this.getResources().getColor(R.color.white));
//            tvRight.setText("积分明细");
//            tvRight.setTextColor(this.getResources().getColor(R.color.white));
//            tvRight.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View v) {
//                    Intent intent = new Intent(WebViewActivityz.this, WebViewActivityt1.class);
//                    intent.putExtra("title", "积分明细");
//                    intent.putExtra("url", Constants.APP_IP + "/wap.php/jifen/awardlist");
//                    startActivity(intent);
//                }
//            });
//        }


        wv.setWebChromeClient(new MyWebChromeClient());
        wv.setWebViewClient(webViewClient);
        WebSettings webSetting = wv.getSettings();
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);   // 支持缩放
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);//这里一定得是false,不然打开的网页中，不能在点击打开了
        webSetting.setLoadWithOverviewMode(true); // no 自适应 屏幕大小界面
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);

        wv.loadUrl(getIntent().getStringExtra("url"));
//        productlist();
        wv.addJavascriptInterface(new AndroidJs(){
            Intent intent = null;
            // 设置头部
            @JavascriptInterface
            public void setTop(String title,boolean flog) {
                back_flog = flog;
                tvTitle.setText(title);
                Message message = new Message();
                if("大厅".equals(title)){
                    message.what = COMPLETED;
                    handler.sendMessage(message);
                    tvRight.setText("交易订单");
                    tvRight.setTextColor(Color.rgb(225,225,225));
                }else{
                    message.what = COMPLETED1;
                    handler.sendMessage(message);
                }
            }

            // 充值VIP会员
            @JavascriptInterface
            public void rechargeVip() {
                getpPayMoneyForm("1","");
            }
            // 实名
            @JavascriptInterface
            public void rechargeReal() {
                getpPayMoneyForm("2","");
            }
            // 开始挖取宝石 and 领取宝石
            @JavascriptInterface
            public void setGemLookVideo(String value) {
                cid = Integer.parseInt(value);
                zklookvideo();
            }
            // 充值币充值
            @JavascriptInterface
            public void goRecharge(String pay_money) {
                getpPayMoneyForm("3",pay_money);
            }
            // 零钱提现
            @JavascriptInterface
            public void gowithdraw(String is_type,String money) {

                Bundle b = new Bundle();
                b.putString("is_type",is_type);
                b.putString("balance", money);
                openActivity(LingqianPutForwardActivity.class, b);
            }
//            // 悬赏任务
//            @JavascriptInterface
//            public void xuanShang() {
//                intent = new Intent(WebViewActivityz.this, WebViewActivity3.class);
//                intent.putExtra("title", "");
//                intent.putExtra("tvRight","首页");
//                intent.putExtra("url",homeItems.get(position).url+"?token="+SPUtils.getStringData(context, "token", ""));
//                startActivity(intent);
//            }
//            // 分享商品
//            @JavascriptInterface
//            public void share_product() {
//                openActivity(MainActivity.class);
//            }
//            // 看视频
//            @JavascriptInterface
//            public void look_video() {
//                cid = 7;
//                lookvideo();
//            }
//           // 邀请好友注册
//            @JavascriptInterface
//            public void invite_friend() {
//                openActivity(MyShareUrlActivity.class);
//            }
//           // 查看消息推送
//            @JavascriptInterface
//            public void look_message() {
//                openActivity(SysMessageActivity.class);
//            }
//           // 商品列表浏览
//            @JavascriptInterface
//            public void browse_product() {
//                intent = new Intent(WebViewActivityz.this, BaoYouActivity.class);
//                intent.putExtra("type", "1");
//                intent.putExtra("jifen_b", true);
//                startActivity(intent);
//            }
//           // 绑定手机号
//            @JavascriptInterface
//            public void save_phone() {
//                openActivity(MyInformationActivity.class);
//            }
//           // 填写微信号
//            @JavascriptInterface
//            public void fill_wechat() {
//                openActivity(MyInformationActivity.class);
//            }
//           // 首次购物
//            @JavascriptInterface
//            public void frist_shop() {
//                openActivity(MyShareUrlActivity.class);
//            }
//           // 首次剪贴板搜索
//            @JavascriptInterface
//            public void frist_search() {
//                showToast("赶紧复制搜索吧");
//            }
//            // 整点领取
//            @JavascriptInterface
//            public void top_left() {
//                cid = 13;
//                lookvideo();
//            }
//            // 5分钟领取
//            @JavascriptInterface
//            public void top_right() {
//                cid = 14;
//                lookvideo();
//            }
//            // 积分翻倍（签到）
//            @JavascriptInterface
//            public void jifen_double(String point) {
//                pointdouble = point;
//                cid = 15;
//                lookvideo();
//            }
//            @JavascriptInterface
//            public void tourl1(String title,String url) {
//                intent = new Intent(WebViewActivityz.this, WebViewActivity.class);
//                intent.putExtra("title", title);
//                intent.putExtra("url", url);
//                startActivity(intent);
//            }


        }, "androidJs");
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == COMPLETED) {
                tvRight.setVisibility(View.VISIBLE);
                tvRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        wv.loadUrl(getIntent().getStringExtra("url").substring(0,getIntent().getStringExtra("url").length()-5)+"user_order");
                    }
                });
            }else if (msg.what == COMPLETED1) {
                tvRight.setVisibility(View.GONE);
            }
        }
    };
    // 赚咖看视频
    private void zklookvideo(){
        Intent intent = new Intent(WebViewActivityz.this, FullScreenVideoActivity.class);
        intent.putExtra("vertical_rit",Constants.vertical_rit);
        intent.putExtra("cid",cid);
        startActivity(intent);
    }
    // 看视频
    private void lookvideo(){
        int sjs = (int) (Math.random()*100);
        int bl = Integer.parseInt(Constants.LOOK_VIDEO_BL);
        if(sjs <= bl){
            Intent intent = new Intent(WebViewActivityz.this, FullScreenVideoActivity.class);
            intent.putExtra("vertical_rit",Constants.vertical_rit);
            intent.putExtra("cid",cid);
            startActivity(intent);
        }else{
            showFullScreenVideoAD();
        }
    }
    private void writeData(){
        String key = "token";
        String val =  SPUtils.getStringData(this, Constants.TOKEN,"");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            wv.evaluateJavascript("window.localStorage.setItem('"+ key +"','"+ val +"');", null);
        } else {
            wv.loadUrl("javascript:localStorage.setItem('"+ key +"','"+ val +"');");
        }
        if (!isReloadFinshed) {
            wv.reload();
            SharedPreferences.Editor editor = getSharedPreferences("JS_CACHE_DATA",MODE_PRIVATE).edit();
            editor.putBoolean("isReloadFinshed",true);
            editor.commit();
            isReloadFinshed = true;
        }
    }

    private void productlist(){
        //适配器
//        highlightsAdapter = new TodayHighlightsAdapter(R.layout.today_highlights_item, todayHighlightsBeans);   // 为你推荐

        //管理器
//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
//        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        recyclerView.setLayoutManager(linearLayoutManager);
//        //添加分割线
//        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
//        recyclerView.setAdapter(highlightsAdapter);
        //取消加载

//        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
//            @Override
//            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//                page1++;
//                getTbkListRequst();
//            }
//
//            @Override
//            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                    wv.evaluateJavascript("javascript:window.getData();", null);
//                } else {
//                    wv.loadUrl("javascript:window.getData();");
//                }
//                page1=1;
//                getTbkListRequst();
//            }
//        });

//         开始刷新
//         refreshLayout.autoRefresh();
//        getTbkListRequst();

    }
    // 购买充值会员
    private void getpPayMoneyForm(String pay_status,String pay_money){
        RequestParams requestParams=new RequestParams();
        requestParams.put("token",SPUtils.getStringData(this,"token",""));
        requestParams.put("pay_method","alipay");
        requestParams.put("pay_status",pay_status);
        requestParams.put("pay_money",pay_money);
        HttpUtils.post(Constants.GET_VIP_FORM, requestParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                showToast(responseString);
            }

            @Override
            public void onStart() {
                super.onStart();
                showLoadingDialog();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    int code = jsonObject.optInt("code");
                    String msg = jsonObject.optString("msg");
                    if (code == 0) {
                        if (responseString.contains("alipay_sdk")) {
                            payZFB(jsonObject.getJSONObject("data").getString("pay_parameters"));
                        }
                    } else {
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private Handler zfbHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                GsonBuilder builder = new GsonBuilder();
                builder.serializeNulls();
                JSONObject object = new JSONObject(builder.create().toJson(msg.obj));
                showToast(object.getString("memo"));
                if(object.getInt("resultStatus")==9000){
//                    Bundle bundle=new Bundle();
//                    bundle.putString("money",allPrice);
//                    bundle.putString("order_num",order_num);
                    finish();
                }
            } catch (JSONException e) {
                showToast("支付发生错误");
            }
        }
    };
    private void payZFB(final String payInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(WebViewActivityz.this);
                Map<String, String> result = alipay.payV2(payInfo, true);
                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                zfbHandle.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }





    /***
     * 获取url 指定name的value;
     * @param url
     * @param name
     * @return
     */
    private String getValueByName(String url, String name) {
        String result = "";
        int index = url.indexOf("?");
        String temp = url.substring(index + 1);
        String[] keyValue = temp.split("&");
        for (String str : keyValue) {
            if (str.contains(name)) {
                result = str.replace(name + "=", "");
                break;
            }
        }
        return result;
    }
    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            writeData();
//            productlist();
            if (!url.contains("oauth.taobao") && !url.contains("oauth.m.taobao"))
                    closeLoadingDialog();
                super.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            if (!url.contains("oauth.taobao") && !url.contains("oauth.m.taobao"))
                showLoadingDialog();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String newurl) {
            if(newurl.startsWith("dmooo://toShare")){
                openActivity(MyShareUrlActivity.class);
                return true;
            }
            if(newurl.startsWith("dmooo://toLogin")){
                openActivity(WelActivity.class);
                return true;
            }
            if (newurl.contains("/error?code=")) {
                SPUtils.saveStringData(WebViewActivityz.this, "coded", getValueByName(newurl, "code"));
                finish();
            }
            try {
                //处理intent协议
                if (newurl.startsWith("intent://")) {
                    Intent intent;
                    try {
                        intent = Intent.parseUri(newurl, Intent.URI_INTENT_SCHEME);
                        intent.addCategory("android.intent.category.BROWSABLE");
                        intent.setComponent(null);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
                            intent.setSelector(null);
                        }
                        List<ResolveInfo> resolves = getPackageManager().queryIntentActivities(intent, 0);
                        if (resolves.size() > 0) {
                            startActivityIfNeeded(intent, -1);
                        }
                        return true;
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }
                }
                // 处理自定义scheme协议
                if (!newurl.startsWith("http")) {
                    try {
                        // 以下固定写法
                        final Intent intent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(newurl));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        startActivity(intent);
                        finish();
                    } catch (Exception e) {
                        // 防止没有安装的情况
                        e.printStackTrace();
                        Uri uri = Uri.parse(getIntent().getStringExtra("url"));
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                        finish();
                    }
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return super.shouldOverrideUrlLoading(view, newurl);
        }
    };

    private class MyWebChromeClient extends WebChromeClient {
        private View mCustomView;
        private CustomViewCallback mCustomViewCallback;

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            super.onShowCustomView(view, callback);
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            mFrameLayout.addView(mCustomView);
            mCustomViewCallback = callback;
            wv.setVisibility(View.GONE);
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        public void onHideCustomView() {
            wv.setVisibility(View.VISIBLE);
            if (mCustomView == null) {
                return;
            }
            mCustomView.setVisibility(View.GONE);
            mFrameLayout.removeView(mCustomView);
            mCustomViewCallback.onCustomViewHidden();
            mCustomView = null;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            super.onHideCustomView();
        }



        public void openFileChooser(ValueCallback<Uri> valueCallback) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }
        // For Android  >= 3.0
        public void openFileChooser(ValueCallback valueCallback, String acceptType) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        //For Android  >= 4.1
        public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType,  String capture) {
            uploadMessage = valueCallback;
            openImageChooserActivity();
        }

        // For Android >= 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            uploadMessageAboveL = filePathCallback;
            openImageChooserActivity();
            return true;
        }



//        protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType)
//        {
//            mUploadMessage = uploadMsg;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("image/*");
//            startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
//        }
//
//        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)
//        {
//            if (uploadMessage != null) {
//                uploadMessage.onReceiveValue(null);
//                uploadMessage = null;
//            }
//
//            uploadMessage = filePathCallback;
//
//            Intent intent = fileChooserParams.createIntent();
//            try
//            {
//                startActivityForResult(intent, REQUEST_SELECT_FILE);
//            } catch (ActivityNotFoundException e)
//            {
//                uploadMessage = null;
//                Toast.makeText(getBaseContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
//                return false;
//            }
//            return true;
//        }
//        //For Android 4.1 only
//        protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)
//        {
//            mUploadMessage = uploadMsg;
//            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//            intent.addCategory(Intent.CATEGORY_OPENABLE);
//            intent.setType("image/*");
//            startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
//        }
//
//        protected void openFileChooser(ValueCallback<Uri> uploadMsg)
//        {
//            mUploadMessage = uploadMsg;
//            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//            i.addCategory(Intent.CATEGORY_OPENABLE);
//            i.setType("image/*");
//            startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
//        }


    }

    private void openImageChooserActivity() {
        //调用自己的图库
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "Image Chooser"),     FILE_CHOOSER_RESULT_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) { //处理返回的图片，并进行上传
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }



    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public void onPause() {
        super.onPause();
        wv.onPause();

    }

    @Override
    public void onResume() {
        super.onResume();
        wv.onResume();
//        if(is_video_id > 0){
//            if(is_video_id == 15){  // 翻倍
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                    wv.evaluateJavascript("javascript:window.tosingin_double();", null);
//                } else {
//                    wv.loadUrl("javascript:window.tosingin_double();");
//                }
//            }else{
//                JifenUtils.record_num(WebViewActivityz.this,is_video_id);
//            }
//            is_video_id = 0;
//        }
//        if (isreload){
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//                wv.evaluateJavascript("javascript:window.getData();", null);
//            } else {
//                wv.loadUrl("javascript:window.getData();");
//            }
//        }
//        isreload = true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(this.lockVideoReceiver);
        wv.destroy();
        if (iad != null) {
            iad.destroy();
        }
    }
    @Override
    public void onBackPressed() {
        if (wv.canGoBack()) {
            wv.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void initListener() {

    }

    @OnClick(R.id.tv_left)
    public void onViewClicked() {
        if (!back_flog){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                wv.evaluateJavascript("javascript: window.history.back();", null);
            } else {
                wv.loadUrl("javascript: window.history.back();");
            }
        }else{
            finish();
            if(main_status){
                Intent intent = new Intent(WebViewActivityz.this, MainActivity.class);
                startActivity(intent);
            }
        }
    }
}
